package com.stx.controller;

import com.stx.domain.*;
import com.stx.service.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
//@RequestMapping("AdminController")
public class AdminController {
    @Resource
    private AdminService as;
    @Resource
    private BuildService bs;
    @Resource
    private CeService ces;
    @Resource
    private CuService cus;
    @Resource
    private DormService ds;
    @Resource
    private StudentService ss;
    @Resource
    private TeacherService ts;

    private List list = new ArrayList();

    private static final Log logger = LogFactory.getLog(StudentController.class);

    /**
     * 登录
     */

    @RequestMapping(value = "adminLogin.do", method = RequestMethod.POST)
    public String adminLogin(String name, String pwd, HttpSession session, Model model) {
        logger.info("POST adminLogin called");
        Admin admin = null;
        try {
            admin = as.adminLogin(name, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (admin != null) {
            session.setAttribute("admin", admin);
            return "admin/menuAdmin";
        } else {
            model.addAttribute("msg", "登录失败！");
            return "redirect:index.jsp";
        }
    }


    @RequestMapping(value = "selectAllTeacher.do", method = RequestMethod.GET)
    public String selectAllTeacher(Model model) {
        logger.info("GET selectAllTeacher called");
        List<Teacher> list = new ArrayList<Teacher>();
        try {
            list = ts.selectTeacher();
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("list", list);
        return "admin/selectAllTeacher";
    }


    @RequestMapping(value = "updateTeacher.do", method = RequestMethod.GET)
    public String doUpdateTeacher(Model model, int no, String name, String tel) {
        logger.info("POST updateTeacher called");
        String name1 = "";
        String tel1 = "";
        try {
            name1 = new String(name.getBytes("ISO-8859-1"), "UTF-8");
            tel1 = new String(tel.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("no", no);
        model.addAttribute("name", name1);
        model.addAttribute("tel", tel1);
        return "admin/updateTeacher";
    }

    @RequestMapping(value = "updateTeacher.do", method = RequestMethod.POST)
    public String doUpdateTeacher(Model model, Teacher teacher) {
        logger.info("POST updateTeacher called");
        try {
            ts.updateTeacher(teacher);
            model.addAttribute("teacher", teacher);
        } catch (Exception e) {
            model.addAttribute("msg", "修改失败！");
            e.printStackTrace();
        }
        return "redirect:selectAllTeacher.do";
    }

    @RequestMapping(value = "deleteTeacher.do")
    public String deleteTeacher(int no) {
        logger.info("deleteTeacher called");
        try {
            ts.teacherDelete(no);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:selectAllTeacher.do";
    }

    /**
     * 添加楼栋管理员
     */
    @RequestMapping(value = "addTeacher.do", method = RequestMethod.GET)
    public String addTeacher() {
        logger.info("GET addTeacher called");
        return "admin/addTeacher";

    }

    @RequestMapping(value = "addTeacher.do", method = RequestMethod.POST)
    public String addTeacher(Teacher teacher) {
        logger.info("POST addTeacher called");
        try {
            ts.addTeacher(teacher);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:selectAllTeacher.do";
    }

    /**
     * 添加学生。导入Excel
     *
     * @throws IOException 使用servlet
     */
/*	@RequestMapping(value="insertStudentForBatch.do",method = RequestMethod.POST)
    public String insertStudentForBatch(@RequestParam Part excelFile) throws IOException{
		logger.info("GET insertStudentForBatch called");
		String headerString = excelFile.getHeader("Content-Disposition");
		InputStream is = excelFile.getInputStream();
		ss.insertStudentForBatch(headerString, is);
		
		return "redirect:selectAllStudentByA.do";
	}*/
	
	/*
	 * 使用springmvc导excel
	 */
    @RequestMapping(value = "insertStudentBySpring.do", method = RequestMethod.POST)
    public String insertStudentForBatch(MultipartFile excelFile) throws IOException {
        logger.info("POST insertStudentForBatch called");
        if (excelFile == null) {
            System.out.println("测试！");
            return null;
        }

        logger.info(excelFile.getOriginalFilename());
        String pathName = excelFile.getOriginalFilename();// 获取上传文件名,包括路径    
        String name = pathName.substring(pathName.lastIndexOf("\\") + 1);// 从全路径中提取文件名    
        long size = excelFile.getSize();
        System.out.println("excel文件大小为：" + size + "字节");
        //也许不会出现一下几种情况但是多判断一下有备无患
        if (name == null || "".equals(name) || size == 0) {
            return null;
        }
        InputStream in = excelFile.getInputStream();
        ss.insertStudentForBatch(name, in);

        return "redirect:selectAllStudentByA.do";
    }

    /**
     * 更新学生
     */
    @RequestMapping(value = "updateStudentByA.do", method = RequestMethod.GET)
    public String updateStudent(Model model, int no, String name, String major) {
        logger.info("GET updateStudentByA called");

        try {
            String name1 = new String(name.getBytes("ISO-8859-1"), "UTF-8");
            String major1 = new String(major.getBytes("ISO-8859-1"), "UTF-8");
            model.addAttribute("name", name1);
            model.addAttribute("major", major1);
            model.addAttribute("no", no);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "admin/updateStudent";
    }

    @RequestMapping(value = "modifyStudentByA.do", method = RequestMethod.POST)
    public String modifyStudent(Model model, Student student) {
        logger.info("POST modifyStudentByA called");

        ss.updateStudent(student);

        return "redirect:selectStudentByA.do";

    }

    /**
     * 删除学生
     */
    @RequestMapping(value = "deleteStudentByA.do", method = RequestMethod.GET)
    public String deleteStudent(int no) {
        logger.info("GET deleteStudent called");

        ss.studentDelete(no);

        return "redirect:selectAllStudentByA.do";
    }

    /**
     * 管理学生
     */
    @RequestMapping(value = "selectAllStudentByA.do", method = RequestMethod.GET)
    public String selectAllStudent(Model model) {
        logger.info("GET selectAllStudent called");
        List<Student> list = new ArrayList<Student>();
        try {
            list = ss.selectStudent();
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("list", list);
        return "admin/selectAllStudent";

    }

    /**
     * 添加学生。导入Excel
     */
	/*@RequestMapping(value="addStudent.do",method = RequestMethod.GET)
	public String addStudent(){
		logger.info("GET addStudent called");
		return "admin/addStudent";
	}*/

    /**
     * 查询楼栋
     */
    @RequestMapping(value = "selectAllBuild.do", method = RequestMethod.GET)
    public String selectAllBuild(Model model) {
        logger.info("GET selectAllBuild called");
        List<Building> list = new ArrayList<Building>();
        try {
            list = bs.selectBuilding();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() == 0)
            model.addAttribute("msg", "没有录入楼栋信息！");
        else
            model.addAttribute("list", list);
        return "admin/selectAllBuild";
    }

    /**
     * 查询宿舍
     */

    @RequestMapping(value = "selectDormByA.do")
    public String selectDormByA(String name, Model model) {
        logger.info("selectDormByA called");
        List<Dorm> list = new ArrayList<Dorm>();
        try {
            list = ds.selectDorm(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() == 0)
            model.addAttribute("msg", "没添加宿舍信息！");
        else {
            model.addAttribute("list", list);
            model.addAttribute("buildingName", name);
        }
        return "admin/showDorm";
    }

    /**
     * 查询显示每个宿舍入住人信息
     *
     * @throws Exception
     */
    @RequestMapping(value = "showLivedStudentByA.do")
    public String showLivedStudentByA(Model model, String name) throws Exception {
        logger.info("showLivedStudentByA called");
        List<Student> list = new ArrayList<Student>();
        list = ss.selectLived(name);
        if (list.size() == 0)
            model.addAttribute("msg", "空宿舍！");
        else {
            model.addAttribute("list", list);
            model.addAttribute("DormName", name);
        }
        return "admin/showLivedStudent";
    }

    /**
     * 换宿舍
     */
    @RequestMapping(value = "changeDorm.do", method = RequestMethod.GET)
    public String changeDorm() {
        logger.info("GET changeDorm called");
        return "admin/changeDorm";
    }

    @RequestMapping(value = "changeDorm.do", method = RequestMethod.POST)
    public String changeDorm(Student student) throws Exception {
        logger.info("POST changeDorm called");
        ss.updateDorm(student);
        return "admin/changeDorm";
    }

    /**
     * 查询缺勤记录
     *
     * @throws Exception
     */
    @RequestMapping(value = "selectAbsentUploadingByA.do")
    public String selectAbsentUploading(Model model) throws Exception {
        logger.info("selectAbsentUploading called");
        List<Absent> list = new ArrayList<Absent>();
        list = cus.selectAbsentUploading();
        model.addAttribute("list", list);
        System.out.println(list.size());
        return "admin/showAbsent";
    }

    /**
     * 确认缺寝
     */
    @RequestMapping(value = "absentConfirm.do")
    public String absentConfirm(int id, int no, String time, String name, String major, String thing, String d, String t) {
        logger.info("absentConfirm called");
        String time1 = "";
        String name1 = "";
        String major1 = "";
        String thing1 = "";
        String t1 = "";
        try {
            time1 = new String(time.getBytes("ISO-8859-1"), "utf-8");
            name1 = new String(name.getBytes("ISO-8859-1"), "utf-8");
            major1 = new String(major.getBytes("ISO-8859-1"), "utf-8");
            thing1 = new String(thing.getBytes("ISO-8859-1"), "utf-8");
            t1 = new String(t.getBytes("ISO-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        Absent absent = new Absent();
        absent.setId(id);
        absent.setTime(time1);
        absent.setNo(no);
        absent.setName(name1);
        absent.setMajor(major1);
        absent.setThing(thing1);
        absent.setD(d);
        absent.setT(t1);

        try {
            ces.absentConfirm(absent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            cus.absentDelete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:selectAbsentUploadingByA.do";
    }

    /**
     * 放弃上传缺寝记录，从cu表中删除，不上传到ce表
     */
    @RequestMapping(value = "absentDeny.do")
    public String absentDeny(int id) {
        logger.info("absentDeny called");
        try {
            cus.absentDelete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:selectAbsentUploadingByA.do";
    }

    /**
     * 修改管理员密码
     */

    @RequestMapping(value = "modifyAdminPwd.do", method = RequestMethod.GET)
    public String modifyAdminPwd(String name, String pwd, Model model) {
        logger.info("GET modifyAdminPwd called");
        model.addAttribute("name", name);
        model.addAttribute("pwd", pwd);
        return "admin/modifyAdminPwd";
    }

    @RequestMapping(value = "modifyAdminPwd.do", method = RequestMethod.POST)
    public String modifyAdminPwd(String originalpassword, String oldpassword, String newpassword, String name, Model model) {
        logger.info("POST modifyAdminPwd called");
        if (originalpassword.equals(oldpassword)) {
            try {
                as.modifyAdminPwd(name, newpassword);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "admin/passwordSuccess";
        } else {
            model.addAttribute("msg", "密码修改失败！");
            return "admin/modifyAdminPwd";
        }
    }
}
